﻿using DevExpress.XtraEditors;
using Lamex.Base;
using Lamex.Common;
using Lamex.Interface;
using Lamex.Library;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mMES.UI
{
    public partial class frmMES_Kanban_Scanning : FrmBaseDataCollection
    {
        System.Timers.Timer t4 = null;
        System.Timers.Timer t2 = null;
        System.Timers.Timer t3 = null;//30分钟后定时器
        string StationName1 = "";
        string StationName2 = "";
        string StationName3 = "";
        string StationName4 = "";
        string StationName5 = "";
        string StationName6 = "";
        SerialPort serialPort1 = new SerialPort();
        SerialPort serialPort2 = new SerialPort();
        SerialPort serialPort3 = new SerialPort();
        SerialPort serialPort4 = new SerialPort();
        SerialPort serialPort5 = new SerialPort();
        SerialPort serialPort6 = new SerialPort();
        SerialPort serialPort7 = new SerialPort();
        SerialPort serialPort8 = new SerialPort();
        string COM1 = "";
        string COM2 = "";
        string COM3 = "";
        string COM4 = "";
        string COM5 = "";
        string COM6 = "";
        string COM7 = "";
        string COM8 = "";
        public int iBeForComSum = 0;
        public int iAfterComSum = 0;
        public int iStanderItime = 200;

        public int maxStandertime = 220;
        public int minStandertime = 180;
        public int standertime = 200;
        public int productTime = 212;
        DataTable dtShowHeader = null;
        // System.Timers.Timer time2 = null;
        string[] arryError = { "MS", "QC", "WS", "CH", "MT", "EQ" };
        string[] arryErrorNOQC = { "MS", "WS", "CH", "MT", "EQ" };
        string[] arryErrorNOEQ = { "MS", "WS", "CH", "MT" };
        string[] arryList = { "MES_QCSA", "MES_QCPA", "MES_QCDA", "MES_QCMA" };
        // string[] arryList_QC = { "MES_QCSZ", "MES_QCPZ", "MES_QCDZ", "MES_QCMZ" };
        string[] arryOrderNumber = { "DK", "PL", "PN", "MG" };
        string[] arryPressStation = { "WS_S06", "WS_S08", "WS_S13", "WS_S16", "WS_S17", "WS_S18", "WS_S19" };
        string strStarTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
        string strBarCode_EN = "刷新成功！";
        DataTable dtUI = Common.GetTable.GetTable_Scan_UI();
        DataTable dtWorkCode = new DataTable();//异常条码表
        DataTable dtPartDetail = new DataTable();//加工产品表
        DataTable dtHR_Station_Info = new DataTable();//站点管理
        string firstTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
        string lastTime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
        double iCycletime = 200;
        double iLimitime = 0.1;

        string UserName = "";
        string PortName_COM = "";
       

        public frmMES_Kanban_Scanning(string StationName)
        {
            InitializeComponent();
            pcTop_M_B.Visible = false;
            this.StationName1 = StationName+"_01.PNG";
            this.StationName2 = StationName + "_02.PNG";
            this.StationName3 = StationName + "_03.PNG";
            this.StationName4 = StationName + "_04.PNG";
            this.StationName5 = StationName + "_05.PNG";
            this.StationName6 = StationName + "_06.PNG";



            UserName = Loginer.CurrentUser.Account;
            if (Lamex.Common.Loginer.CurrentUser.Account == "TY Chan" || Lamex.Common.Loginer.CurrentUser.Account == "Rocky He" || Lamex.Common.Loginer.CurrentUser.Account == "TX02820" || Lamex.Common.Loginer.CurrentUser.Account == "TX02869" || Lamex.Common.Loginer.CurrentUser.Account == "TX02951")
            {
                UserName = "WS_"+ StationName;
                
            }
            //gc_pcTop_L.Text = UserName + "岗位或产品信息";
            //gc_pcTop_L.Text = "";
            //gc_pcTop_L.Text = UserName ;
            //
            this.Text = UserName;

            LoadGroupList();

            //groupControl6.Text = "CNC_C本月产量";
            ShowProductSumProgressBar();

            Lamex.Common.IniFile ini = new IniFile(Application.StartupPath + "\\config\\SavePath.ini");
            string VedioPath = ini.IniReadValue("Path Configuration", "VedioPath").ToString();

            axWindowsMediaPlayer1.uiMode = "None";
            axWindowsMediaPlayer1.currentPlaylist.appendItem(axWindowsMediaPlayer1.newMedia(VedioPath));
            axWindowsMediaPlayer1.settings.setMode("loop", true);
            axWindowsMediaPlayer1.settings.mute = true;
            axWindowsMediaPlayer1.Ctlcontrols.play();
            //List<string> lst = new List<string>();
            //lst.Add(@"C:\Users\JackLi\Desktop\Frm\Player\bin\Debug\Learning course\Avail Open Office Solution (Lamex version).mp4");

            //windowMediaPlayer1.GetVideo(lst);
            //frmOEEControlUI1.ShowProcessList("1",200);
            //frmQualityPassRate1.ShowProcessList("1", 200);

            string QualityPath = @"\\tx-fs10\TX-FS1\LAMEX\MES\SysSource\Image\Quality\"+UserName+@"\";
            string QualityPath1 = QualityPath + StationName1;
            string QualityPath2 = QualityPath + StationName2;
            string QualityPath3 = QualityPath + StationName3;
            string QualityPath4 = QualityPath + StationName4;
            string QualityPath5 = QualityPath + StationName5;
            string QualityPath6 = QualityPath + StationName6;
            #region"加载控位图片"


            //if (File.Exists(QualityPath1))
            //{
            //    picProcess1.Load(QualityPath1);
            //}
            //if (File.Exists(QualityPath2))
            //{
            //    picProcess2.Load(QualityPath2);
            //}
            //if (File.Exists(QualityPath3))
            //{
            //    picProcess3.Load(QualityPath3);
            //}
            //if (File.Exists(QualityPath4))
            //{
            //    picProcess4.Load(QualityPath4);
            //}
            //if (File.Exists(QualityPath5))
            //{
            //    picProcess5.Load(QualityPath5);
            //}
            //if (File.Exists(QualityPath6))
            //{
            //    picProcess6.Load(QualityPath6);
            //}
            #endregion

        }
        
        private void frmMES_Kanban_Scanning_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            //如果是非'WS_'用户，直接刷屏（每30S)


            //如果是'WS_'用户，不需要初始化屏幕，只进行排班人员检查，如果有排班信息直接加载岗位信息
            //否则，提示用户，并不加载系统


            DataTable dtItme = BaseBuildSql.GetDataTableBySql(@" select a.* from  [dbo].[HR_Work_ShiftRec]  a 
                                join (select top 1* from  [HR_Station_Info]  where STATION_NAME='" + UserName + @"') b on b.DEPARTMENT=a.DEPARTMENT
                                where   a.EFFECTIVE_DATE<=  CONVERT(nvarchar(10),GETDATE(),120) and CONVERT(nvarchar(10),GETDATE(),120)<CONVERT(nvarchar(10), a. EXPIRY_DATE,120)
                            ");
            if (dtItme.Rows.Count == 0)
            {
                XtraMessageBox.Show("没有排班人员！无法操作");
                return;
            }




            if (!DesignMode)
            {

                dtWorkCode = Common.GetDataTable.GetWork_Barcode();
                dtPartDetail = Common.GetDataTable.GetPart_Detailed();
                dtHR_Station_Info = Common.GetDataTable.GetHR_Station_Info();
                //开启COM扫描
                //InitCom();
                //读取扫描表最后一个条码
                GetLastLamp();
            }
            gc_pcTop_L.Text = UserName + gc_pcTop_L.Text;
            //InitLoad();

            //timer1_Tick(null, null);
            string seatPath = "";
            //if (UserName == "WS_P05")
            //    seatPath = @"\\tx-fs10\tx-fs1\LAMEX\MES\SysSource\Image\Product\MES_PD_P05_Lcnc.PNG";

            //if (File.Exists(seatPath))
            //{
            //    picTop3.Visible = true;
            //    labelControl1.Visible = false;
            //    picTop3.Load(seatPath);
            //    //picProcess1.Load(QualityPath1);
            //}
            //t1 = new System.Timers.Timer(5000 * 4);
            //t1.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp1);
            //t1.AutoReset = true;
            //t1.Enabled = true;
            //t1.Start();

            groupControl1.Visible = true;
            //groupControl2.Visible = true;
            groupControl3.Visible = true;
            // groupControl4.Visible = true;
            groupControl5.Visible = true;
            //groupControl6.Visible = true;
            ShowCNCList();
        }
        public void Timer_TimesUp1(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (t4 != null)
                {
                    t4.Enabled = false;
                    t4.Stop();
                    t4.Dispose();
                }
                IsPicVisible();
                if (t2 == null)
                {
                    t2 = new System.Timers.Timer(5000 * 4);
                    t2.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp2);
                    t2.AutoReset = true;
                    t2.Enabled = true;
                    t2.Start();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "123");
            }
        }
        public void Timer_TimesUp2(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (t2 != null)
                {
                    t2.Enabled = false;
                    t2.Stop();
                    t2.Dispose();
                }

                IsPieVisible();
                if (t4 == null)
                {
                    t4 = new System.Timers.Timer(5000 * 2);
                    t4.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp1);
                    t4.AutoReset = true;
                    t4.Enabled = true;
                    t4.Start();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "124");
            }
        }
        public void GetLastLamp()
        {
            //得到不是撤销标识且不是MES_MG11111的最后两个条码
            DataTable dt_S08 = Common.GetDataTable.GetNoCancelNoMG_Top2(firstTime, UserName);
            if (dt_S08.Rows.Count > 0)
            {
                string Barcode = dt_S08.Rows[0]["BARCODE"].ToString();
                ChargeLamp(Barcode);
            }
        }
        private void frmMES_Kanban_Scanning_Resize(object sender, EventArgs e)
        {
            int pcBottom_W = this.pcBottom.Width;
            //groupControl1.Width = pcBottom_W / 3;
            ////groupControl2.Width = pcBottom_W / 6;
            //groupControl3.Width = pcBottom_W / 3;
            ////groupControl4.Width = pcBottom_W / 6;
            //groupControl5.Width = pcBottom_W / 3;
            ////groupControl6.Width = pcBottom_W / 6;
            int sum = dtShowHeader.Rows.Count;
            foreach (Control g in pcBottom.Controls)
            {
                if (g is GroupControl)
                {
                    GroupControl uc = g as GroupControl;
                    uc.Width = pcBottom_W / sum;
                }
            }

        }
        /// <summary>

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        private void txtPartBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == 13)
                {
                    //空或长度不够，直接返回
                    if (string.IsNullOrEmpty(txtPartBarCode.Text) || txtPartBarCode.Text.Length < 6) return;

                    DataTable dt = BaseBuildSql.GetDataTableBySql("select * from [dbo].[HR_Process_CycleTime] where PRODUCT='" + txtPartBarCode.Text + "'");

                    if (dt.Rows.Count != 0)
                    {
                        iCycletime = double.Parse(dt.Rows[0]["CYCLETIME"].ToString());
                        maxStandertime = int.Parse((iCycletime + double.Parse(dt.Rows[0]["LIMIT_RATE"].ToString()) * double.Parse(dt.Rows[0]["CYCLETIME"].ToString())).ToString());
                        minStandertime = int.Parse((iCycletime - double.Parse(dt.Rows[0]["LIMIT_RATE"].ToString()) * double.Parse(dt.Rows[0]["CYCLETIME"].ToString())).ToString());

                        iStanderItime = int.Parse((iCycletime).ToString());
                        productTime = int.Parse(dt.Rows[0]["CHANGEOVER_TIME"].ToString());
                    }
                    //iCycletime=

                    if (txtPartBarCode.Text.Substring(0, 3) == "MES" || txtPartBarCode.Text.Substring(0, 3) == "LMX" ||
                        dtPartDetail.Select("Order_Number='" + txtPartBarCode.Text.Trim() + "'").Length > 0)
                    {

                        //得到最后一个条码
                        DataTable dt_LastBarCode = Common.GetDataTable.GetLastBarCode_StationName(UserName);
                        //得到不是撤销标识的最后两个条码
                        DataTable dt_S08_1 = Common.GetDataTable.GetNoCancel_Top2(firstTime, UserName);
                        //得到不是撤销标识且不是MES_MG11111的最后两个条码
                        DataTable dt_S08_2 = Common.GetDataTable.GetNoCancelNoMG_Top2(firstTime, UserName);
                        //得到当天MES_MG00000的记录
                        DataTable dt_MG00000 = Common.GetDataTable.GetHR_Scan_Record_MG00000(firstTime, lastTime, UserName);

                        //1、【MES_MG00000】上一码下线码MES_MG99999或未开线码MES_MG88888  
                        if (txtPartBarCode.Text.Trim() == "MES_MG00000")
                        {
                            if (dt_LastBarCode.Rows[0]["BARCODE"].ToString() == "MES_MG99999" ||
                                dt_LastBarCode.Rows[0]["BARCODE"].ToString() == "MES_MG88888")
                            {
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                Common.ScanRecordHelper.Insert("", "MES_MG00000", 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                ShowCNCList();
                                ClearControl();
                                return;
                            }

                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }

                        //2、【MES_MG88888】上一码下线码MES_MG99999
                        if (txtPartBarCode.Text.Trim() == "MES_MG88888")
                        {
                            if (dt_LastBarCode.Rows[0]["BARCODE"].ToString() == "MES_MG99999")
                            {
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                Common.ScanRecordHelper.Insert("", "MES_MG88888", 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                ShowCNCList();
                                ClearControl();
                                return;
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }
                        //3、【MES_MG99999】下线码
                        if (txtPartBarCode.Text.Trim() == "MES_MG99999")
                        {
                            //当天当前工作站无记录时可以扫入
                            if (dt_S08_2.Rows.Count <= 0)
                            {
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                Common.ScanRecordHelper.Insert("", txtPartBarCode.Text, 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                endTime();//关闭定时器
                                ShowCNCList();
                                ClearControl();
                                return;
                            }

                            string strTemp = dt_S08_2.Rows[0]["BARCODE"].ToString();
                            if (dtWorkCode.Select("BARCODE_SN='" + strTemp + "'").Length > 0)
                            {
                                string strColor = dtWorkCode.Select("BARCODE_SN='" + strTemp + "'").CopyToDataTable().Rows[0]["LIGHT_STATE"].ToString();
                                if (strColor == "Green")
                                {
                                    string Location_Code = "", Scanner_No = "";
                                    GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                    Common.ScanRecordHelper.Insert("", txtPartBarCode.Text, 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                    Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                    GetDisplayInfo();
                                    ChargeLamp(txtPartBarCode.Text.Trim());
                                    endTime();//关闭定时器
                                    ShowCNCList();
                                    ClearControl();
                                    return;
                                }
                                else
                                {
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                    #region 写入Error_Log表
                                    string strError = "";
                                    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                    {
                                        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                    }
                                    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                    #endregion
                                    ClearControl();
                                    return;
                                }
                            }
                            // update by Bill 20191216 robin要求增加此逻辑判断
                            else if (strTemp.Contains("PD") || strTemp.Contains("DK") || strTemp.Contains("PN") || strTemp.Contains("PL"))
                            {
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                Common.ScanRecordHelper.Insert("", txtPartBarCode.Text, 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                endTime();//关闭定时器
                                ShowCNCList();
                                ClearControl();
                                //ShowAllInfo("【" + txtPartBarCode.Text + "】扫入成功！");
                                return;
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }

                        //if (dt_S08_2.Rows.Count <= 0)
                        //{
                        //    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                        //    #region 写入Error_Log表
                        //    string strError = "";
                        //    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                        //    {
                        //        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                        //    }
                        //    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                        //    #endregion
                        //    ClearControl();
                        //    return;
                        //}

                        //if (txtPartBarCode.Text.Trim() == "MES_MG88888" || txtPartBarCode.Text.Trim() == "MES_MG00000")
                        //{
                        //    if (dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG88888" || dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG00000")
                        //    {
                        //        ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                        //        #region 写入Error_Log表
                        //        string strError = "";
                        //        if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                        //        {
                        //            strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                        //        }
                        //        Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                        //        #endregion
                        //        ClearControl();
                        //        return;
                        //    }
                        //}
                       
                       

                        //4、【MES_MG11111】撤销码
                        if (txtPartBarCode.Text.Trim() == "MES_MG11111")
                        {
                            //不可以连续扫描两次撤销码
                            if (dt_S08_1.Rows[0]["BARCODE"].ToString() == "MES_MG11111")
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                            //dt_S08_2最少有一条记录
                            if (dt_S08_2.Rows.Count == 1)
                            {
                                if (dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG00000")
                                {
                                    string Location_Code = "", Scanner_No = "";
                                    GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                    endTime();//停止定时器
                                    Common.ScanRecordHelper.Update(dt_S08_2.Rows[0]["BARCODE"].ToString(), dt_S08_2.Rows[0]["SCAN_TIME"].ToString());
                                    Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                    Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                    GetDisplayInfo();
                                    ChargeLamp(txtPartBarCode.Text.Trim());
                                    StopLamp();//停止信号灯-全为灰色
                                    ShowCNCList();
                                    ClearControl();
                                    return;
                                }
                            }
                            else
                            {
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                //更新撤销标识
                                Common.ScanRecordHelper.Update(dt_S08_2.Rows[0]["BARCODE"].ToString(), dt_S08_2.Rows[0]["SCAN_TIME"].ToString());
                                //当前颜色变化
                                // ChargeLamp(txtPartBarCode.Text.Trim());
                                //信号灯颜色变化为上上一条数据颜色
                                ChargeLamp(dt_S08_2.Rows[1]["BARCODE"].ToString());
                                //写入数据库
                                Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                ShowCNCList();
                                ClearControl();
                                return;
                            }
                        }

                        //5、产品码【MES_PD_S08_Array】
                        if (txtPartBarCode.Text.Trim().Substring(0, 6) == "MES_PD")
                        {
                            InitProduct();
                            // if (UserName.Contains("S08"))
                            if (arryPressStation.Contains(UserName) && dt_MG00000.Rows.Count > 0)
                            {
                                if (dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG00000" ||
                                     dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_CH00001")
                                {
                                    string Location_Code = "", Scanner_No = "";
                                    GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                    Common.ScanRecordHelper.Insert("", txtPartBarCode.Text, 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                                    Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                    GetDisplayInfo();
                                    ChargeLamp(txtPartBarCode.Text.Trim());
                                    ClearControl();
                                    strStarTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                                    InsertRecord();//按当前时间刷新一次
                                    ShowCNCList();
                                    //StartTime();//开启定时器
                                    return;
                                }
                                else
                                {
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                    #region 写入Error_Log表
                                    string strError = "";
                                    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                    {
                                        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                    }
                                    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                    #endregion
                                    ClearControl();
                                    return;
                                }
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }

                        }

                        //6、停线报告
                        if (arryError.Contains(txtPartBarCode.Text.Trim().Substring(4, 2)) &&
                           txtPartBarCode.Text.Trim().Substring(6, 5) == "00000")
                        {

                            if (dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG99999" ||
                                dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG00000" ||
                            dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG88888" ||
                            (arryError.Contains(dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(4, 2)) &&
                            dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(6, 5) == "00000"))
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }                          
                            string Location_Code = "", Scanner_No = "";
                            GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                            //写入数据库 
                            Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, txtPartBarCode.Text.Trim().Substring(4, 2));
                            Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                            GetDisplayInfo();
                            //信号灯颜色变化
                            ChargeLamp(txtPartBarCode.Text.Trim());
                            SendMailerCheck(txtPartBarCode.Text);//mail Send
                            ClearControl();
                            InsertRecord();//接收回之前的数据
                            ShowCNCList();
                            return;
                        }

                        //7、不停线报告
                        if (arryError.Contains(txtPartBarCode.Text.Trim().Substring(4, 2)) &&
                          txtPartBarCode.Text.Trim().Substring(6, 5) == "90000")
                        {
                            //发邮件
                            string Location_Code = "", Scanner_No = "";
                            GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                            //写入数据库 
                            Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, "");
                            Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                            GetDisplayInfo();
                            //信号灯颜色变化
                            ChargeLamp(txtPartBarCode.Text.Trim());
                            SendMailerCheck(txtPartBarCode.Text);//mail Send
                            ClearControl();
                            InsertRecord();//接收回之前的数据
                            ShowCNCList();
                            return;
                        }

                        //8、确认人
                        if (txtPartBarCode.Text.Trim().Substring(0, 6) == "LMX_TX")
                        {
                            if (arryError.Contains(dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(4, 2))
                                    && dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(6, 5) == "00000")
                            {
                                DataTable dtWorks = Common.GetDataTable.GetWorksInfo(txtPartBarCode.Text.Trim());
                                if (dtWorks.Rows.Count > 0)
                                {
                                    string[] arryCode = dtWorks.Rows[0]["OPRATION_CODE"].ToString().Split(';');
                                    if (arryCode.Contains(dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(4, 2)))
                                    {
                                        string Location_Code = "", Scanner_No = "";
                                        GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                        DateTime t1 = Convert.ToDateTime(dt_S08_2.Rows[0]["SCAN_TIME"].ToString());//前一个条码时间
                                        DateTime t2 = DateTime.Now;//当前时间
                                        TimeSpan t3 = t2 - t1;//时间差
                                        Common.ScanRecordHelper.Insert("", txtPartBarCode.Text, 0, Math.Ceiling(t3.TotalSeconds), t2, Scanner_No, Location_Code, UserName, dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(4, 2));
                                        Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                        GetDisplayInfo();
                                        ChargeLamp(txtPartBarCode.Text.Trim());
                                        ShowAllInfo("【" + txtPartBarCode.Text + "】扫入成功！");
                                        ShowCNCList();
                                        ClearControl();
                                        return;
                                    }
                                    else
                                    {
                                        ShowAllInfo("【" + txtPartBarCode.Text + "】无权限操作！");
                                        ClearControl();
                                        return;
                                    }
                                }
                                else
                                {
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                    #region 写入Error_Log表
                                    string strError = "";
                                    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                    {
                                        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                    }
                                    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                    #endregion
                                    ClearControl();
                                    return;
                                }
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }

                        //9、异常码 生产异常 当前码存在MS、WS、CH、MT中有任一种
                        if (arryErrorNOEQ.Contains(txtPartBarCode.Text.Trim().Substring(4, 2)) &&
                             txtPartBarCode.Text.Trim().Substring(6, 5) != "00000" &&
                              txtPartBarCode.Text.Trim().Substring(6, 5) != "90000" &&
                            IsInt(txtPartBarCode.Text.Trim().Substring(6, 5)))
                        {
                            //前一码必须为LMX_TX*****
                            if (dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(0, 6) == "LMX_TX")
                            {
                                //必须为同类型才可以扫描
                                if (txtPartBarCode.Text.Trim().Substring(0, 6) != (dt_S08_2.Rows[1]["BARCODE"].ToString().Substring(0, 6)))
                                {
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                    #region 写入Error_Log表
                                    string strError = "";
                                    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                    {
                                        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                    }
                                    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                    #endregion
                                    ClearControl();
                                    return;
                                }
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                //写入数据库
                                DateTime t1 = Convert.ToDateTime(dt_S08_2.Rows[0]["SCAN_TIME"].ToString());//前一个条码时间
                                DateTime t2 = DateTime.Now;//当前时间
                                TimeSpan t3 = t2 - t1;//时间差
                                Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, Math.Ceiling(t3.TotalSeconds), t2, Scanner_No, Location_Code, UserName, txtPartBarCode.Text.Trim().Substring(4, 2));
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                //信号灯颜色变化
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                ShowCNCList();
                                ClearControl();
                                // StartTime();//开启定时器
                                return;
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }

                        //10、【EQCL】
                        if (txtPartBarCode.Text.Trim().Substring(0, 8) == "MES_EQCL")
                        {
                            if (dt_S08_2.Rows[1]["BARCODE"].ToString() == "MES_EQ00000")
                            {
                                if (dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(0, 6) == "LMX_TX")
                                {
                                    string Location_Code = "", Scanner_No = "";
                                    GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                    //写入数据库 
                                    Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, txtPartBarCode.Text.Trim().Substring(4, 2));
                                    Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                    GetDisplayInfo();
                                    //信号灯颜色变化
                                    ChargeLamp(txtPartBarCode.Text.Trim());
                                    ClearControl();
                                    InsertRecord();//接收回之前的数据
                                    ShowCNCList();
                                    return;
                                }
                                else
                                {
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                    #region 写入Error_Log表
                                    string strError = "";
                                    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                    {
                                        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                    }
                                    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                    #endregion
                                    ClearControl();
                                    return;
                                }
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }

                        //11、【MES_EQ00001】
                        if (txtPartBarCode.Text.Trim().Substring(0, 6) == "MES_EQ" &&
                           txtPartBarCode.Text.Trim().Substring(6, 5) != "00000" &&
                            txtPartBarCode.Text.Trim().Substring(6, 5) != "90000" &&
                            IsInt(txtPartBarCode.Text.Trim().Substring(6, 5)))
                        {
                            if (dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(0, 8) == "MES_EQCL")
                            {
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                DateTime t1 = Convert.ToDateTime(dt_S08_2.Rows[1]["SCAN_TIME"].ToString());//上上一个条码时间
                                DateTime t2 = DateTime.Now;//当前时间
                                TimeSpan t3 = t2 - t1;//时间差
                                Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, Math.Ceiling(t3.TotalSeconds), t2, Scanner_No, Location_Code, UserName, txtPartBarCode.Text.Trim().Substring(4, 2));
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                //信号灯颜色变化
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                ClearControl();

                                InsertRecord();//接收回之前的数据
                                ShowCNCList();
                                return;
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }

                        //12、QC
                        if (arryList.Contains(txtPartBarCode.Text.Trim().Substring(0, 8)))
                        {
                            //前一码必须为LMX_TX*****
                            if (dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(0, 6) == "LMX_TX" &&
                                dt_S08_2.Rows[1]["BARCODE"].ToString() == "MES_QC00000")
                            {
                                //必须为同类型才可以扫描
                                // if (txtPartBarCode.Text.Trim().Substring(4, 2) != (dt_S08_2.Rows[1]["BARCODE"].ToString().Substring(4, 2)))
                                if (UserName.Substring(3, 1) != txtPartBarCode.Text.Trim().Substring(6, 1))
                                {
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                    #region 写入Error_Log表
                                    string strError = "";
                                    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                    {
                                        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                    }
                                    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                    #endregion
                                    ClearControl();
                                    return;
                                }
                                //写入数据库
                                //DateTime t1 = Convert.ToDateTime(dt_S08_2.Rows[0]["SCAN_TIME"].ToString());//前一个条码时间
                                //DateTime t2 = DateTime.Now;//当前时间
                                //TimeSpan t3 = t2 - t1;//时间差
                                //if (txtScanerQty.Text.Trim().Length <= 0)
                                //{
                                //    ShowAllInfo("请先输入扫描数量！");
                                //    return;
                                //}
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), 0, 0, DateTime.Now, Scanner_No, Location_Code, UserName, txtPartBarCode.Text.Trim().Substring(4, 2));
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, 0, Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                //信号灯颜色变化
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                SendMailerCheck(txtPartBarCode.Text);//mail Send
                                ShowCNCList();
                                ClearControl();
                                // StartTime();//开启定时器
                                return;
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }
                        //13、加工产品（DK、DKSJ\...）
                        if (arryOrderNumber.Contains(txtPartBarCode.Text.Trim().Substring(0, 2)))
                        {
                            if (dt_MG00000.Rows.Count > 0)
                            {
                                if (dt_S08_2.Rows[0]["BARCODE"].ToString() == "MES_MG00000" ||
                                    arryOrderNumber.Contains(dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(0, 2)) ||
                                   (arryError.Contains(dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(4, 2)) &&
                                   dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(6, 5) != "00000") &&
                                   IsInt(dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(6, 5)))
                                {
                                    if (txtScanerQty.Text.Trim().Length <= 0)
                                    {
                                        ShowAllInfo("请先输入扫描数量！");
                                        return;
                                    }
                                    string Location_Code = "", Scanner_No = "";
                                    GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                    DataTable dt_Order_Number = Common.GetDataTable.GetOrder_Number_Time(firstTime, lastTime, UserName);
                                    DateTime t1 = Convert.ToDateTime(dt_Order_Number.Rows[0]["SCAN_TIME"].ToString());//前一个条码时间
                                    DateTime t2 = DateTime.Now;//当前时间
                                    TimeSpan t3 = t2 - t1;//时间差
                                    Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), Convert.ToInt32(txtScanerQty.Text), Math.Ceiling((t3.TotalSeconds) - Common.ScanRecordHelper.SCAN_TIME_LENGTH(firstTime, lastTime, UserName)), t2, Scanner_No, Location_Code, UserName, "");
                                    Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, Convert.ToInt32(txtScanerQty.Text), Location_Code, strBarCode_EN);
                                    GetDisplayInfo();
                                    //信号灯颜色变化
                                    ChargeLamp(txtPartBarCode.Text.Trim());
                                    //开启信号灯变化-强制变绿色
                                    StopLamp();
                                    StartLamp("Green");
                                    StartTime();
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】扫入成功！");
                                    ShowCNCList();
                                    ClearControl();
                                    return;
                                }
                                else
                                {
                                    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                    #region 写入Error_Log表
                                    string strError = "";
                                    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                    {
                                        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                    }
                                    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                    #endregion
                                    ClearControl();
                                    return;
                                }
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }

                        //14 【MES_QC】
                        if (txtPartBarCode.Text.Trim().Substring(0, 6) == "MES_QC" &&
                             txtPartBarCode.Text.Trim().Substring(6, 5) != "90000")
                        {
                            //前一码包含arryList
                            if (arryList.Contains(dt_S08_2.Rows[0]["BARCODE"].ToString().Substring(0, 8)))
                            {
                                //必须为同类型才可以扫描
                                // if (txtPartBarCode.Text.Trim().Substring(4, 2) != (dt_S08_2.Rows[1]["BARCODE"].ToString().Substring(4, 2)))
                                //if (UserName.Substring(3, 1) != txtPartBarCode.Text.Trim().Substring(6, 1))
                                //{
                                //    ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                //    #region 写入Error_Log表
                                //    string strError = "";
                                //    if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                //    {
                                //        strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                //    }
                                //    Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                //    #endregion
                                //    ClearControl();
                                //    return;
                                //}
                                //写入数据库
                                DateTime t1 = Convert.ToDateTime(dt_S08_2.Rows[1]["SCAN_TIME"].ToString());//前一个条码时间
                                DateTime t2 = DateTime.Now;//当前时间
                                TimeSpan t3 = t2 - t1;//时间差
                                if (txtScanerQty.Text.Trim().Length <= 0)
                                {
                                    ShowAllInfo("请先输入扫描数量！");
                                    return;
                                }
                                string Location_Code = "", Scanner_No = "";
                                GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                                Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), Convert.ToInt32(txtScanerQty.Text), Math.Ceiling(t3.TotalSeconds), t2, Scanner_No, Location_Code, UserName, txtPartBarCode.Text.Trim().Substring(4, 2));
                                Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, Convert.ToInt32(txtScanerQty.Text), Location_Code, strBarCode_EN);
                                GetDisplayInfo();
                                //信号灯颜色变化
                                ChargeLamp(txtPartBarCode.Text.Trim());
                                SendMailerCheck(txtPartBarCode.Text);//mail Send
                                ShowCNCList();
                                ClearControl();
                                // StartTime();//开启定时器
                                return;
                            }
                            else
                            {
                                ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                                #region 写入Error_Log表
                                string strError = "";
                                if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                                {
                                    strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                                }
                                Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                                #endregion
                                ClearControl();
                                return;
                            }
                        }
                    }
                    else
                    {
                        ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                        #region 写入Error_Log表
                        string strError = "";
                        if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                        {
                            strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                        }
                        Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                        #endregion
                        ClearControl();
                        return;
                    }

                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }


        //滚动显示信息值
        public void ShowLblInfo()
        {
            string lbl1 = lblInfo_1.Text;
            string lbl2 = lblInfo_2.Text;
            string lbl3 = lblInfo_3.Text;
            string lbl4 = lblInfo_4.Text;
            if (lblInfo_3.IsHandleCreated)
                Invoke(new Action(() =>
                {
                    lblInfo_3.Text = lbl4;
                }));
            if (lblInfo_2.IsHandleCreated)
                Invoke(new Action(() =>
                {
                    lblInfo_2.Text = lbl3;
                }));
            if (lblInfo_1.IsHandleCreated)
                Invoke(new Action(() =>
                {
                    lblInfo_1.Text = lbl2;
                }));
        }
        //显示所有信息值
        public void ShowAllInfo(string Error)
        {
            ShowLblInfo();
            if (lblInfo_4.IsHandleCreated)
                Invoke(new Action(() =>
                {
                    lblInfo_4.Text = Error;
                }));
        }
        //清空控件值
        public void ClearControl()
        {
            Invoke(new Action(() =>
            {
                txtPartBarCode.Text = "";
                txtScanerQty.Text = "";
                //txtQty.Enabled = false;
            }));
        }

        private void InitLoad()
        {
            try
            {
                string strP01 = UserName + "_01";
                string strP02 = UserName + "_02";
                DataTable dtWorkInfo = Lamex.Base.BaseBuildSql.GetDataTableBySql(@"select  a.*,c.*  from [dbo].[HR_Station_Info] a 
                                                                                left join[dbo].[HR_Location_Record] b on b.LOCATION_CODE = a.LOCATION_CODE
                                                                                left join[dbo].[HR_Workers_Info] c on c.WORKER_NO = b.DUTY_OPERATOR
                                                                                where a.STATION_NAME = '" + UserName + "' and(a.LOCATION_CODE = '"+ strP01 + "' or a.LOCATION_CODE = '"+ strP02 + "') ");

                if (dtWorkInfo.Rows.Count != 0)
                {
                    //优先加载加载图片
                    if (dtWorkInfo.Rows[0]["PHOTO"].ToString() != "")
                    {
                        lb_Name1.Visible = false;
                        picTop1.Visible = true;
                        byte[] image1 = (byte[])dtWorkInfo.Rows[0]["PHOTO"];
                        picTop1.Image = Lamex.Common.DataConverter.ByteToImg(image1);
                        lb_Name1.Text = dtWorkInfo.Rows[0]["WORKER_NAME"].ToString();

                    }
                    else
                    {
                        lb_Name1.Visible = true;
                        picTop1.Visible = false;
                        lb_Name1.Text = dtWorkInfo.Rows[0]["WORKER_NAME"].ToString();

                    }

                    if (dtWorkInfo.Rows[1]["PHOTO"].ToString() != "")
                    {
                        lb_Name2.Visible = false;
                        picTop2.Visible = true;
                        byte[] image2 = (byte[])dtWorkInfo.Rows[1]["PHOTO"];
                        picTop2.Image = Lamex.Common.DataConverter.ByteToImg(image2);
                        lb_Name2.Text = dtWorkInfo.Rows[1]["WORKER_NAME"].ToString();


                    }
                    else
                    {
                        lb_Name2.Visible = true;
                        picTop2.Visible = false;
                        lb_Name2.Text = dtWorkInfo.Rows[1]["WORKER_NAME"].ToString();
                        picTop2.Load(@"\\tx-fs10\tx-fs1\LAMEX\MES\SysSource\Image\Product\MES_HR_TX00274.jpg");

                    }
                }

                DataTable dtDuty = Lamex.Base.BaseBuildSql.GetDataTableBySql(@"
                                                                               select * from [dbo].[HR_Station_Info] a 
                                                                                left join  HR_Location_Record b on b.LOCATION_CODE=a.LOCATION_CODE
                                                                                left join HR_Workers_Info c on c.WORKER_NO=b.DUTY_OPERATOR
                                                                                 where STATION_NAME = '" + UserName + "'");
                if (dtDuty.Rows.Count != 0)
                {
                    string strName = "";
                    //int maxLength = dtDuty.AsEnumerable().SelectMany(row => row.ItemArray.OfType<string>()).Max(o => o.Length);
                    //object maxobject = dtDuty.Compute("Max(LOCATION_NAME)", "");
                    //maxLength = Convert.ToInt32(maxobject);
                    int maxLength = 0;
                    foreach (DataRow dr in dtDuty.Rows)
                    {
                        if (dr["LOCATION_NAME"].ToString().Length > maxLength)
                        {
                            maxLength = dr["LOCATION_NAME"].ToString().Length;
                        }
                    }


                    foreach (DataRow dr in dtDuty.Rows)
                    {
                        int colLength = dr["LOCATION_NAME"].ToString().Length;
                        int blankLength = maxLength - colLength;
                        string strBlank = "";
                        int m = 0;
                        for (int i = 0; i < blankLength; i++)
                        {
                            strBlank += " ";
                            m = 1;
                        }
                        if (m == 1)
                            strName += "   " + strBlank + dr["LOCATION_NAME"].ToString() + "： " + dr["WORKER_NAME"].ToString() + "\r\n";
                        else
                            strName += " " + dr["LOCATION_NAME"].ToString() + "： " + dr["WORKER_NAME"].ToString() + "\r\n";
                        labelControl1.Text = strName;
                    }
                }


                //string seatPath = @"L:\LAMEX\MES\SysSource\Image\Product\MES_PD_S08_Array.jpg";
                //if (File.Exists(seatPath))
                //{
                //    picTop3.Visible = true;
                //    labelControl1.Visible = false;
                //    picTop3.Load(seatPath);
                //    //picProcess1.Load(QualityPath1);
                //}
                //string qualityPath = @"\\tx-fs10\TX-FS1\LAMEX\MES\SysSource\Image\Quality\WS_S08\"+ QualityPhoto + ".PNG";
                //if (File.Exists(qualityPath))
                //{
                //    picTop3.Load(qualityPath);
                //}
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        //插入数据库-因有图片类型，故需重新inser语句
        private int Write(string strSql, byte[] imageBytes)
        {
            string sConn = SqlConfiguration.CurrentConnectionString;

            using (SqlConnection conn = new SqlConnection(sConn))
            {
                using (SqlCommand cmd = new SqlCommand(strSql, conn))
                {
                    try
                    {
                        conn.Open();
                        SqlParameter sqlParameter = new SqlParameter("@image", SqlDbType.Image);
                        sqlParameter.Value = imageBytes;
                        cmd.Parameters.Add(sqlParameter);
                        int rows = cmd.ExecuteNonQuery();
                        conn.Close();
                        return rows;
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            }
        }

        private void picTop3_Click(object sender, EventArgs e)
        {

            //XtraMessageBox.Show(pcTop_M_T.Height.ToString()+":"+pcTop_M_T.Width.ToString());
        }

        private void labelControl1_Click(object sender, EventArgs e)
        {
            //picTop3.Visible = true;
            //labelControl1.Visible = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ShowCNCList();
            //firstTime = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
            //lastTime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " 00:00:00";
            //InsertRecord();
            //Timer_TimesUp(null, null);

            ////groupControl1.Text = "装背铁";

            //if (frmSeatControlUI1.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        groupControl1.Text = "CNC_A今日产量";
            //        bool Isvalue = true;
            //        bool ReValue = false;
            //        frmSeatControlUI1.ShowProcessList("1", maxStandertime, minStandertime, standertime, productTime, UserName, ref Isvalue, ref ReValue);
            //        if (ReValue != false)
            //        {
            //            if (Isvalue == true)
            //            {
            //                groupControl1.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl1.LookAndFeel.SkinMaskColor = Color.Green;
            //            }
            //            else
            //            {
            //                groupControl1.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl1.LookAndFeel.SkinMaskColor = Color.Red;
            //            }
            //        }

            //    }));
            //if (frmSeatControlUI2.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        groupControl2.Text = "CNC_A本月产量";
            //        bool Isvalue = true;
            //        bool ReValue = false;
            //        frmSeatControlUI2.ShowProcessList("2", maxStandertime, minStandertime, standertime, productTime, UserName, ref Isvalue, ref ReValue);
            //        if (ReValue != false)
            //        {
            //            if (Isvalue == true)
            //            {
            //                groupControl2.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl2.LookAndFeel.SkinMaskColor = Color.Green;
            //            }
            //            else
            //            {
            //                groupControl2.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl2.LookAndFeel.SkinMaskColor = Color.Red;
            //            }
            //        }
            //    }));
            //if (frmSeatControlUI3.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        groupControl3.Text = "CNC_B今日产量";
            //        bool Isvalue = true;
            //        bool ReValue = false;
            //        frmSeatControlUI3.ShowProcessList("3", maxStandertime, minStandertime, standertime, productTime, UserName, ref Isvalue, ref ReValue);
            //        if (ReValue != false)
            //        {
            //            if (Isvalue == true)
            //            {
            //                groupControl3.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl3.LookAndFeel.SkinMaskColor = Color.Green;
            //            }
            //            else
            //            {
            //                groupControl3.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl3.LookAndFeel.SkinMaskColor = Color.Red;
            //            }
            //        }
            //    }));
            //if (frmSeatControlUI4.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        groupControl4.Text = "CNC_B本月产量";
            //        bool Isvalue = true;
            //        bool ReValue = false;
            //        frmSeatControlUI4.ShowProcessList("4", maxStandertime, minStandertime, standertime, productTime, UserName, ref Isvalue, ref ReValue);
            //        if (ReValue != false)
            //        {
            //            if (Isvalue == true)
            //            {
            //                groupControl4.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl4.LookAndFeel.SkinMaskColor = Color.Green;
            //            }
            //            else
            //            {
            //                groupControl4.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl4.LookAndFeel.SkinMaskColor = Color.Red;
            //            }
            //        }
            //    }));
            //if (frmSeatControlUI5.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        groupControl5.Text = "CNC_C今日产量";
            //        bool Isvalue = true;
            //        bool ReValue = false;
            //        frmSeatControlUI5.ShowProcessList("5", maxStandertime, minStandertime, standertime, productTime, UserName, ref Isvalue, ref ReValue);
            //        if (ReValue != false)
            //        {
            //            if (Isvalue == true)
            //            {
            //                groupControl5.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl5.LookAndFeel.SkinMaskColor = Color.Green;
            //            }
            //            else
            //            {
            //                groupControl5.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl5.LookAndFeel.SkinMaskColor = Color.Red;
            //            }
            //        }
            //    }));
            //if (frmSeatControlUI6.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        groupControl6.Text = "CNC_C本月产量";
            //        bool Isvalue = true;
            //        bool ReValue = false;
            //        frmSeatControlUI6.ShowProcessList("6", maxStandertime, minStandertime, standertime, productTime, UserName, ref Isvalue, ref ReValue);
            //        if (ReValue != false)
            //        {
            //            if (Isvalue == true)
            //            {
            //                groupControl6.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl6.LookAndFeel.SkinMaskColor = Color.Green;
            //            }
            //            else
            //            {
            //                groupControl6.LookAndFeel.UseDefaultLookAndFeel = false;
            //                groupControl6.LookAndFeel.SkinMaskColor = Color.Red;
            //            }
            //        }
            //    }));

            //if (frmQualityPassRate1.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        frmQualityPassRate1.ShowProcessList("1", 200);
            //    }));

            //if (frmProductQualityControlUI1.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        frmProductQualityControlUI1.ShowProcessList("1", 200, UserName);
            //    }));

            //if (frmProductRate1.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        frmProductRate1.ShowProcessList("1", int.Parse(iCycletime.ToString()), UserName);
            //    }));

            //if (frmOEEControlUI1.IsHandleCreated)
            //    Invoke(new Action(() =>
            //    {
            //        frmOEEControlUI1.ShowProcessList("1", 200, UserName);
            //    }));


        }
        //开启定时器
        private void StartTime()
        {
            //time1 = new System.Timers.Timer();
            //time1.Enabled = true;
            //time1.Interval = 1000 * 10; //执行间隔时间,单位为毫秒; 
            //time1.Start();
            //time1.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            this.Invoke((MethodInvoker)delegate
            {
                timer1.Enabled = true;
                timer1.Interval = 1000 * 30; //执行间隔时间,单位为毫秒; 
                timer1.Start();
            });
        }
        //关闭定时器
        private void endTime()
        {
            this.Invoke((MethodInvoker)delegate
            {
                timer1.Enabled = false;
                timer1.Stop();
            });
        }
        //获取不存在[LamexMESManager].[dbo].[HR_Scan_Record]的记录
        private void InsertRecord()
        {
            //            try
            //            {
            //                string sql_ST_S08_Receive_Data = @"select NOId,ngNo,writetime from  [Edgeband_Program].[dbo].[ST_S08_Receive_Data] 
            // where NOId not in(select NOID from [LamexMESManager].[dbo].[HR_Scan_Record] where NOID is not null)
            //and writetime>'" + strStarTime + "' and startIndex != 2 and wordtime != 0";
            //                DataTable dt = BaseBuildSql.GetDataTableBySql(sql_ST_S08_Receive_Data);
            //                DataTable dtNew = Common.GetTable.GetTable_Scan_Record();//动态保存扫描记录表

            //                if (dt.Rows.Count > 0)
            //                {
            //                    for (int i = 0; i < dt.Rows.Count; i++)
            //                    {
            //                        string strSCANNER_NO = "";
            //                        string strLOCATION_CODE = "";
            //                        switch (dt.Rows[i]["ngNo"].ToString())
            //                        {
            //                            case "1":
            //                                strLOCATION_CODE = "WS_S08_11";
            //                                break;
            //                            case "2":
            //                                strLOCATION_CODE = "WS_S08_12";
            //                                break;
            //                            case "3":
            //                                strLOCATION_CODE = "WS_S08_13";
            //                                break;
            //                            case "4":
            //                                strLOCATION_CODE = "WS_S08_14";
            //                                break;
            //                            case "5":
            //                                strLOCATION_CODE = "WS_S08_15";
            //                                break;
            //                            case "6":
            //                                strLOCATION_CODE = "WS_S08_16";
            //                                break;
            //                            case "7":
            //                                strLOCATION_CODE = "WS_S08_17";
            //                                break;
            //                        }
            //                        string sql_HR_Station_Info = @"SELECT DUTY_OPERATOR FROM  [LamexMESManager].[dbo].[HR_Location_Record] WHERE LOCATION_CODE='" + strLOCATION_CODE + "'";
            //                        DataTable dtTemp = BaseBuildSql.GetDataTableBySql(sql_HR_Station_Info);
            //                        if (dtTemp.Rows.Count > 0)
            //                        {
            //                            strSCANNER_NO = dtTemp.Rows[0]["DUTY_OPERATOR"].ToString();
            //                        }
            //                        //写入扫描记录表
            //                        DataRow dr = dtNew.NewRow();
            //                        dr["NOID"] = dt.Rows[i]["NOId"].ToString();
            //                        dr["BARCODE"] = Convert.ToDateTime(dt.Rows[i]["writetime"]).ToString("yyyyMMddHHmmssfff");
            //                        dr["SCAN_QTY"] = 1;
            //                        dr["TIME_LENGTH"] = 0;
            //                        dr["SCAN_TIME"] = Convert.ToDateTime(dt.Rows[i]["writetime"]).ToString("yyyy-MM-dd HH:mm:ss.fff");
            //                        dr["SCANNER_NO"] = strSCANNER_NO;
            //                        dr["LOCATION_CODE"] = strLOCATION_CODE;
            //                        dr["STATION_NAME"] = UserName;
            //                        dtNew.Rows.Add(dr);
            //                        //写入UI临时显示表
            //                        DataRow drUI = dtUI.NewRow();
            //                        drUI["BARCODE"] = Convert.ToDateTime(dt.Rows[i]["writetime"]).ToString("yyyyMMddHHmmssfff");
            //                        drUI["SCAN_TIME"] = Convert.ToDateTime(dt.Rows[i]["writetime"]).ToString("HH:mm:ss");
            //                        drUI["LOCATION_CODE"] = strLOCATION_CODE;
            //                        drUI["SCAN_QTY"] = 1;
            //                        drUI["SCANNER_NO"] = strSCANNER_NO;
            //                        drUI["BARCODE_CN"] = strLOCATION_CODE + ":" + strBarCode_EN;
            //                        dtUI.Rows.Add(drUI);

            //                    }
            //                    //批量插入数据库
            //                    if (BaseBuildSql.ExcuteInsert(dtNew, "HR_Scan_Record"))
            //                    {
            //                        //扫描信息显示
            //                        if (dtUI.Rows.Count > 0)
            //                        {
            //                            if (gcMid_B.IsHandleCreated)
            //                            {
            //                                gcMid_B.Invoke(new MethodInvoker(() =>
            //                                {
            //                                    DataView dv = dtUI.DefaultView;
            //                                    dv.Sort = "SCAN_TIME Desc";
            //                                    dtUI = dv.ToTable();
            //                                    gcMid_B.DataSource = dtUI;
            //                                    gridView1.BestFitColumns();
            //                                    this.gridView1.OptionsView.ColumnAutoWidth = false;
            //                                }));
            //                            }
            //                            //实时显示扫描状态
            //                            DataTable dtTop4 = DtSelectTop(4, dtUI);

            //                            if (dtTop4.Rows.Count == 1)
            //                            {
            //                                Invoke(new Action(() => { lblInfo_4.Text = dtTop4.Rows[0]["BARCODE_CN"].ToString(); }));
            //                            }
            //                            else if (dtTop4.Rows.Count == 2)
            //                            {
            //                                Invoke(new Action(() => { lblInfo_4.Text = dtTop4.Rows[0]["BARCODE_CN"].ToString(); }));
            //                                Invoke(new Action(() => { lblInfo_3.Text = dtTop4.Rows[1]["BARCODE_CN"].ToString(); }));
            //                            }
            //                            else if (dtTop4.Rows.Count == 3)
            //                            {
            //                                Invoke(new Action(() => { lblInfo_4.Text = dtTop4.Rows[0]["BARCODE_CN"].ToString(); }));
            //                                Invoke(new Action(() => { lblInfo_3.Text = dtTop4.Rows[1]["BARCODE_CN"].ToString(); }));
            //                                Invoke(new Action(() => { lblInfo_2.Text = dtTop4.Rows[2]["BARCODE_CN"].ToString(); }));
            //                            }
            //                            else
            //                            {
            //                                Invoke(new Action(() => { lblInfo_4.Text = dtTop4.Rows[0]["BARCODE_CN"].ToString(); }));
            //                                Invoke(new Action(() => { lblInfo_3.Text = dtTop4.Rows[1]["BARCODE_CN"].ToString(); }));
            //                                Invoke(new Action(() => { lblInfo_2.Text = dtTop4.Rows[2]["BARCODE_CN"].ToString(); }));
            //                                Invoke(new Action(() => { lblInfo_1.Text = dtTop4.Rows[3]["BARCODE_CN"].ToString(); }));
            //                            }
            //                        }
            //                    }
            //                }

            //            }
            //catch (Exception ex)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            //}
        }
        /// <summary> 
        /// 获取DataTable前几条数据 
        /// </summary> 
        /// <param name="TopItem">前N条数据</param> 
        /// <param name="oDT">源DataTable</param> 
        /// <returns></returns> 
        public static DataTable DtSelectTop(int TopItem, DataTable oDT)
        {
            if (oDT.Rows.Count < TopItem) return oDT;

            DataTable NewTable = oDT.Clone();
            DataRow[] rows = oDT.Select("1=1", "SCAN_TIME Desc");
            for (int i = 0; i < TopItem; i++)
            {
                NewTable.ImportRow((DataRow)rows[i]);
            }
            return NewTable;
        }
        //获取异常条码
        public DataTable GetWork_Barcode()
        {
            string sql = @"SELECT [BARCODE_SN]
      ,[LIGHT_STATE]
      ,[BARCODE_TYPE]
      ,[BARCODE_DESC]    
  FROM [LamexMESManager].[dbo].[HR_Work_Barcode]";
            dtWorkCode = BaseBuildSql.GetDataTableBySql(sql);
            return dtWorkCode;
        }
        //扫描信息显示
        public void GetDisplayInfo()
        {
            if (dtUI.Rows.Count > 0)
            {
                if (gcMid_B.IsHandleCreated)
                {
                    gcMid_B.Invoke(new MethodInvoker(() =>
                    {
                        DataView dv = dtUI.DefaultView;
                        dv.Sort = "SCAN_TIME Desc";
                        dtUI = dv.ToTable();
                        gcMid_B.DataSource = dtUI;
                        gridView1.BestFitColumns();
                        this.gridView1.OptionsView.ColumnAutoWidth = false;
                    }));
                }
            }
        }
        //停止信号灯
        public void StopLamp()
        {
            LampGreen.Invoke(new Action(() =>
            {

                LampGreen.LampColor = new System.Drawing.Color[] { System.Drawing.Color.Silver, System.Drawing.Color.Silver };
                LampGreen.TwinkleSpeed = 0;
            }));
            //LampRed.Invoke(new Action(() =>
            //{

            //    this.LampRed.LampColor = new System.Drawing.Color[] { System.Drawing.Color.Silver, System.Drawing.Color.Silver };
            //    LampRed.TwinkleSpeed = 0;
            //}));
            //LampYellow.Invoke(new Action(() =>
            //{
            //    LampYellow.LampColor = new System.Drawing.Color[] { System.Drawing.Color.Silver, System.Drawing.Color.Silver };
            //    LampYellow.TwinkleSpeed = 0;
            //}));
            //LampBlue.Invoke(new Action(() =>
            //{
            //    LampBlue.LampColor = new System.Drawing.Color[] { System.Drawing.Color.Silver, System.Drawing.Color.Silver };
            //    LampBlue.TwinkleSpeed = 0;
            //}));
        }
        //开启信号灯
        public void StartLamp(string Color)
        {
            switch (Color)
            {
                case "Green":
                    LampGreen.Invoke(new Action(() =>
                    {

                        LampGreen.LampColor = new System.Drawing.Color[] {
        System.Drawing.Color.Green,
        System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))))
                        };
                        LampGreen.TwinkleSpeed = 100;
                        lblStatus.Text = "正常生产";

                    }));
                    break;
                case "Red":
                    LampGreen.Invoke(new Action(() =>
                    {
                        this.LampGreen.LampColor = new System.Drawing.Color[] {
                System.Drawing.Color.Red,
        System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(77)))), ((int)(((byte)(59)))))
                        };
                        LampGreen.TwinkleSpeed = 100;
                        lblStatus.Text = "暂停生产";

                    }));
                    break;
                case "Yellow":
                    LampGreen.Invoke(new Action(() =>
                    {

                        LampGreen.LampColor = new System.Drawing.Color[] {
        System.Drawing.Color.Yellow,
        System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128)))))
                    };
                        LampGreen.TwinkleSpeed = 100;
                        lblStatus.Text = "缺料等待";
                    }));
                    break;
                case "Blue":
                    LampGreen.Invoke(new Action(() =>
                    {
                        LampGreen.LampColor = new System.Drawing.Color[] {
        System.Drawing.Color.Blue,
        System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))))
                    };
                        LampGreen.TwinkleSpeed = 100;
                        lblStatus.Text = "准备生产";
                    }));
                    break;
            }
        }
        //信号灯颜色变化
        public void ChargeLamp(string BarCode)
        {
            if (BarCode.Trim().Length > 6)
            {
                if (BarCode.Substring(0, 6) == "MES_PD" || arryOrderNumber.Contains(BarCode.Substring(0,2)))
                {
                    //开启信号灯变化
                    StopLamp();
                    StartLamp("Green");
                    StartTime();
                    ShowLblInfo();
                    InitProduct();
                    if (lblInfo_4.IsHandleCreated)
                        Invoke(new Action(() =>
                        {
                            lblInfo_4.Text = "产品码扫描成功！";
                        }));
                }
                else
                {
                    if (dtWorkCode.Select("BARCODE_SN='" + BarCode + "'").Length > 0)
                    {
                        string strColor = dtWorkCode.Select("BARCODE_SN='" + BarCode + "'").CopyToDataTable().Rows[0]["LIGHT_STATE"].ToString();
                        string strDesc = dtWorkCode.Select("BARCODE_SN='" + BarCode + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                        //开启信号灯变化
                        StopLamp();
                        StartLamp(strColor);
                        if (strColor == "Green")
                        {
                            StartTime();
                            InitProduct();
                        }
                        else
                            endTime();
                        ShowLblInfo();
                        if (lblInfo_4.IsHandleCreated)
                            Invoke(new Action(() =>
                            {
                                lblInfo_4.Text = string.IsNullOrEmpty(strDesc) ? BarCode : strDesc;
                            }));
                    }
                }
            }
        }
        #region 扫描COM实现
        public string[] GetRunCom()
        {
            string[] str = SerialPort.GetPortNames();
            return str;
        }
        public void InitCom()
        {
            string[] str = GetRunCom();
            iBeForComSum = str.Count();
            if (str == null)
            {
                return;
            }
            Lamex.Common.IniFile ini = new Lamex.Common.IniFile(Application.StartupPath + "\\config\\ComSetting.ini");
            COM1 = ini.IniReadValue("COM Configuration", "COM1");
            COM2 = ini.IniReadValue("COM Configuration", "COM2");
            COM3 = ini.IniReadValue("COM Configuration", "COM3");
            COM4 = ini.IniReadValue("COM Configuration", "COM4");
            COM5 = ini.IniReadValue("COM Configuration", "COM5");
            COM6 = ini.IniReadValue("COM Configuration", "COM6");
            COM7 = ini.IniReadValue("COM Configuration", "COM7");
            COM8 = ini.IniReadValue("COM Configuration", "COM8");
            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == COM1)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(s, serialPort1);
                }
                else if (s == COM2)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(s, serialPort2);
                }
                else if (s == COM3)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(s, serialPort3);
                }
                else if (s == COM4)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(s, serialPort4);
                }
                else if (s == COM5)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(s, serialPort5);
                }
                else if (s == COM6)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(s, serialPort6);
                }
                else if (s == COM7)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(s, serialPort7);
                }
                else if (s == COM8)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(s, serialPort8);
                }

            }
            //StartTime();
            //alterTime();
        }

        public void InitSingleCom(string PortName)
        {
            string[] str = GetRunCom();

            //添加串口项目
            foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
            {
                //获取有多少个COM口
                if (s == PortName)
                {
                    serialPort1 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort1);
                }
                else if (s == PortName)
                {
                    serialPort2 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort2);
                }
                else if (s == PortName)
                {
                    serialPort3 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort3);
                }
                else if (s == PortName)
                {
                    serialPort4 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort4);
                }
                else if (s == PortName)
                {
                    serialPort5 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort5);
                }
                else if (s == PortName)
                {
                    serialPort6 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort6);
                }
                else if (s == PortName)
                {
                    serialPort7 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort7);
                }
                else if (s == PortName)
                {
                    serialPort8 = new SerialPort();
                    InstanceSerialPort(PortName, serialPort8);
                }

                System.Threading.Thread.Sleep(1000);

            }
        }
        /// <summary>
        /// 实例化串行端口资源
        /// </summary>
        public void InstanceSerialPort(string comName, SerialPort serialPort)
        {


            try
            {
                //实例化串行端口
                //SerialPort serialPort = new SerialPort();
                //端口名  注:因为使用的是USB转RS232 所以去设备管理器中查看一下虚拟com口的名字
                serialPort.PortName = comName;
                //波特率
                serialPort.BaudRate = 9600;
                //奇偶校验
                serialPort.Parity = Parity.None;
                //停止位
                serialPort.StopBits = StopBits.One;
                //数据位
                serialPort.DataBits = 8;
                //忽略null字节
                serialPort.DiscardNull = true;

                //接收事件
                serialPort.DataReceived += serialPort_DataReceived;
                //开启串口
                serialPort.Open();
                //alterTime();
            }
            catch (Exception ex)
            {
                //XtraMessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            try
            {
                ReceiveData(serialPort);
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }

        public void ReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            try
            {
                //防止数据接收不完整 线程sleep(100)
                System.Threading.Thread.Sleep(100);

                string str = serialPort.ReadExisting();
                PortName_COM = serialPort.PortName;
                if (str == string.Empty)
                {
                    return;
                }
                else
                {
                    txtPartBarCode.Invoke(new Action(() => { txtPartBarCode.Text = str.Replace("\r", "").Trim(); txtPartBarCode.Focus(); SendKeys.Send("\r\n"); }));

                }
            }
            catch (Exception ex)
            {
                //SetMessage(ex.Message, serialPort.PortName);
            }
        }




        public void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (COM1 == serialPort1.PortName)
            {
                if (serialPort1.IsOpen != true)
                {
                    serialPort1.Close();
                    InitSingleCom(serialPort1.PortName);
                }
            }
            if (COM2 == serialPort2.PortName)
            {
                if (serialPort2.IsOpen != true)
                {
                    serialPort2.Close();
                    InitSingleCom(serialPort2.PortName);
                }
            }
            if (COM3 == serialPort3.PortName)
            {
                if (serialPort3.IsOpen != true)
                {
                    serialPort3.Close();
                    InitSingleCom(serialPort3.PortName);
                }
            }
            if (COM4 == serialPort4.PortName)
            {
                if (serialPort4.IsOpen != true)
                {
                    serialPort4.Close();
                    InitSingleCom(serialPort4.PortName);
                }

            }
            if (COM5 == serialPort5.PortName)
            {
                if (serialPort5.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort5.PortName);
                }
            }
            if (COM6 == serialPort6.PortName)
            {
                if (serialPort6.IsOpen != true)
                {
                    serialPort6.Close();
                    InitSingleCom(serialPort6.PortName);
                }
            }
            if (COM7 == serialPort7.PortName)
            {
                if (serialPort7.IsOpen != true)
                {
                    serialPort7.Close();
                    InitSingleCom(serialPort7.PortName);
                }
            }
            if (COM8 == serialPort8.PortName)
            {
                if (serialPort8.IsOpen != true)
                {
                    serialPort5.Close();
                    InitSingleCom(serialPort8.PortName);
                }
            }
        }

        public void CloseReceiveData()
        {
            serialPort1.Dispose();
            serialPort2.Dispose();
            serialPort3.Dispose();
            serialPort4.Dispose();
            serialPort5.Dispose();
            serialPort6.Dispose();
            serialPort7.Dispose();
            serialPort8.Dispose();
            serialPort1.Close();
            serialPort2.Close();
            serialPort3.Close();
            serialPort4.Close();
            serialPort5.Close();
            serialPort6.Close();
            serialPort7.Close();
            serialPort8.Close();
            if (t4 != null)
            {
                t4.Stop();
                t4.Dispose();
            }

            if (t2 != null)
            {
                t2.Stop();
                t2.Dispose();
            }
            if (t3 != null)
            {
                t3.Stop();
                t3.Dispose();
            }

        }
        #endregion

        private void frmMES_Kanban_Scanning_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.Yes == XtraMessageBox.Show("是否确定要关闭界面", "", MessageBoxButtons.YesNo))
            {
                CloseReceiveData();
                e.Cancel = false;
            }
            else
                e.Cancel = true;

        }


        #region"进度条"
        private void ShowProductSumProgressBar()
        {
            //int iPass = 0;
            //DataTable dtPass = BaseBuildSql.GetDataTableBySql(@" select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120)  group by CONVERT(nvarchar(6),BARCODE)
            //                    union all
            //                    select m.SCAN_QTY-n.SCAN_QTY SCAN_QTY,m.MES_PD from (select sum(SCAN_QTY) SCAN_QTY,'MES_PD' as MES_PD from HR_Scan_Record 
            //                    where LOCATION_CODE='WS_S08_09' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120)
            //                    group by LOCATION_CODE) m 
            //                    left join (select   sum(SCAN_QTY) SCAN_QTY,CONVERT(nvarchar(6),BARCODE) BARCODE,'MES_PD' as MES_PD from HR_Scan_Record  where CONVERT(nvarchar(6),BARCODE)='MES_QC'  group by CONVERT(nvarchar(6),BARCODE)
            //                    ) n on n.MES_PD=m.MES_PD ");

            //DataRow dr = dtPass.Select(" 1=1 and BARCODE='MES_PD'").FirstOrDefault();
            //if (dr == null) iPass = 0;
            //else
            //    iPass = int.Parse(dr["SCAN_QTY"].ToString());
            progressBar.Visible = true;
            progressBar.Properties.Minimum = 0;
            progressBar.Properties.Maximum = 100;
            progressBar.Properties.Step = 10;
            progressBar.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
            progressBar.Position = 0;
            progressBar.Properties.ShowTitle = true;
            progressBar.Properties.PercentView = true;

            string startime = "2019-11-12 08:00:00";
            DateTime time = Convert.ToDateTime(startime);
            TimeSpan span = DateTime.Now.Subtract(time);
            progressBar.Position = span.Hours * 10;





        }

        #endregion

        private void txtScanerQty_KeyPress(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是退格和数字，则屏蔽输入
            if (!(e.KeyChar == '\b' || (e.KeyChar >= '0' && e.KeyChar <= '9')))
            {
                e.Handled = true;

            }
            if (e.KeyChar == 13)
            {
                if (txtScanerQty.Text.Trim().Length <= 0)
                {
                    ShowAllInfo("请先输入扫描数量！");
                    return;
                }
                if (txtPartBarCode.Text.Trim().Length <= 5)
                {
                    ShowAllInfo("请先扫描条码！");
                    return;
                }
                DataTable dt_S08_2 = Common.GetDataTable.GetNoCancelNoMG_Top2(firstTime, UserName);
                if (txtPartBarCode.Text.Trim().Substring(4, 2) == "QC")
                {
                    //前一码必须为LMX_TX*****
                    if (dt_S08_2.Rows[0]["BARCODE"].ToString().Contains("LMX_TX"))
                    {
                        //必须为同类型才可以扫描
                        if (txtPartBarCode.Text.Trim().Substring(4, 2) != (dt_S08_2.Rows[1]["BARCODE"].ToString().Substring(4, 2)))
                        {
                            ShowAllInfo("【" + txtPartBarCode.Text + "】为非法码！");
                            #region 写入Error_Log表
                            string strError = "";
                            if (dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").Length > 0)
                            {
                                strError = dtWorkCode.Select("BARCODE_SN='" + txtPartBarCode.Text + "'").CopyToDataTable().Rows[0]["BARCODE_DESC"].ToString();
                            }
                            Common.ScanRecordHelper.Insert_Error(txtPartBarCode.Text, strError, UserName, DateTime.Now);
                            #endregion
                            ClearControl();
                            return;
                        }
                        string Location_Code = "", Scanner_No = "";
                        GetHRInfo(UserName + "_" + PortName_COM, txtPartBarCode.Text.Trim(), out Location_Code, out Scanner_No);
                        //写入数据库
                        DateTime t1 = Convert.ToDateTime(dt_S08_2.Rows[1]["SCAN_TIME"].ToString());//前一个条码时间
                        DateTime t2 = DateTime.Now;//当前时间
                        TimeSpan t3 = t2 - t1;//时间差     
                        Common.ScanRecordHelper.Insert("", txtPartBarCode.Text.Trim(), Convert.ToInt32(txtScanerQty.Text), t3.TotalSeconds, t2, Scanner_No, Location_Code, UserName, txtPartBarCode.Text.Trim().Substring(4, 2));
                        Common.ScanRecordHelper.Insert_GridControl(dtUI, txtPartBarCode.Text.Trim(), Scanner_No, Convert.ToInt32(txtScanerQty.Text), Location_Code, strBarCode_EN);
                        GetDisplayInfo();
                        //信号灯颜色变化
                        ChargeLamp(txtPartBarCode.Text.Trim());
                        ClearControl();
                        //StartTime();//开启定时器
                        return;
                    }
                }
            }
        }

        public override void DoResetCom(IButtonInfo sender)
        {
            InitCom();
            base.DoResetCom(sender);
        }

        private void frmSeatControlUI1_DoubleClick(object sender, EventArgs e)
        {
            IsPieVisible();

        }

        private void frmSeatControlUI2_DoubleClick(object sender, EventArgs e)
        {
            IsPieVisible();
        }

        private void frmSeatControlUI3_DoubleClick(object sender, EventArgs e)
        {
            IsPieVisible();
        }

        private void frmSeatControlUI4_DoubleClick(object sender, EventArgs e)
        {
            IsPieVisible();
        }

        private void frmSeatControlUI5_DoubleClick(object sender, EventArgs e)
        {
            IsPieVisible();
        }

        private void frmSeatControlUI6_DoubleClick(object sender, EventArgs e)
        {
            IsPieVisible();
        }

        private void picProcess1_DoubleClick(object sender, EventArgs e)
        {
            IsPicVisible();
        }

        private void picProcess2_DoubleClick(object sender, EventArgs e)
        {
            IsPicVisible();
        }

        private void picProcess3_DoubleClick(object sender, EventArgs e)
        {
            IsPicVisible();
        }

        private void picProcess5_DoubleClick(object sender, EventArgs e)
        {
            IsPicVisible();
        }

        private void picProcess6_DoubleClick(object sender, EventArgs e)
        {
            IsPicVisible();
        }


        private void IsPieVisible()
        {

        }
        private void IsPicVisible()
        {

        }

        private void labelControl1_DoubleClick(object sender, EventArgs e)
        {
            picTop3.Visible = true;
            labelControl1.Visible = false;
        }

        private void picTop3_DoubleClick(object sender, EventArgs e)
        {
            picTop3.Visible = false;
            labelControl1.Visible = true;
        }


        private void ShowCNCList()
        {

            
            foreach (Control c in pcBottom.Controls)
            {
                if (c is GroupControl)
                {
                    GroupControl g = c as GroupControl;
                    foreach(Control p in g.Controls)
                    {
                        if (p is LabelControl)
                        {
                            LabelControl uc = p as LabelControl;
                            
                            foreach (DataRow dr in dtShowHeader.Rows)
                            {
                                if (uc.Name == dr["LOCATION_NAME"].ToString())
                                {
                                    DataTable _dt = BaseBuildSql.GetDataTableBySql(@"
                        select a.LOCATION_NAME,ISNULL( b.SCAN_QTY,0) SCAN_QTY  from HR_Station_Info a
                            left join  (select LOCATION_CODE  ,STATION_NAME,case when  ISNULL( sum(ISNULL( SCAN_QTY,0)),0)=0 then 0 else sum(ISNULL( SCAN_QTY,0)) end  as SCAN_QTY  from [dbo].[HR_Scan_Record] where BARCODE like 'PL%' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) and LOCATION_CODE='" + uc.Name + "' and STATION_NAME='" + UserName + @"'
                        group by LOCATION_CODE ,STATION_NAME) b on a.LOCATION_NAME=b.LOCATION_CODE and b.STATION_NAME=a.STATION_NAME
                        where a.LOCATION_NAME='" + uc.Name + "'  and a.STATION_NAME='" + UserName + @"'");

                                    if (_dt.Rows.Count != 0)
                                    {
                                        uc.Text = _dt.Rows[0]["SCAN_QTY"].ToString();
                                    }
                                    else
                                        uc.Text = "0";
                                }

                            }
                            
                        }
                    }
                }
                
            }
            

            ////DataSet ds = BaseBuildSql.GetDataSetBySql(@
            //select a.DEVEICE_COM,ISNULL( b.SCAN_QTY,0) SCAN_QTY  from HR_Station_Info a
            // left join  (select LOCATION_CODE  ,STATION_NAME,case when  ISNULL( sum(ISNULL( SCAN_QTY,0)),0)=0 then 0 else sum(ISNULL( SCAN_QTY,0)) end  as SCAN_QTY  from [dbo].[HR_Scan_Record] where BARCODE like 'PL%' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) and LOCATION_CODE='WS_P05_COM3' and STATION_NAME='" + UserName+ @"'
            //group by LOCATION_CODE ,STATION_NAME) b on a.LOCATION_CODE=b.LOCATION_CODE and b.STATION_NAME=a.STATION_NAME
            //where a.DEVEICE_COM='WS_P05_COM4'  and a.STATION_NAME='" + UserName + @"'

            //select a.DEVEICE_COM,ISNULL( b.SCAN_QTY,0) SCAN_QTY  from HR_Station_Info a
            // left join  (select LOCATION_CODE  ,STATION_NAME,case when  ISNULL( sum(ISNULL( SCAN_QTY,0)),0)=0 then 0 else sum(ISNULL( SCAN_QTY,0)) end  as SCAN_QTY  from [dbo].[HR_Scan_Record] where BARCODE like 'PL%' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) and LOCATION_CODE='WS_P05_COM4' and STATION_NAME='" + UserName + @"'
            //group by LOCATION_CODE ,STATION_NAME) b on a.LOCATION_CODE=b.LOCATION_CODE and b.STATION_NAME=a.STATION_NAME
            //where a.DEVEICE_COM='WS_P05_COM5'  and a.STATION_NAME='" + UserName + @"'

            //select a.DEVEICE_COM,ISNULL( b.SCAN_QTY,0) SCAN_QTY  from HR_Station_Info a
            // left join  (select LOCATION_CODE  ,STATION_NAME,case when  ISNULL( sum(ISNULL( SCAN_QTY,0)),0)=0 then 0 else sum(ISNULL( SCAN_QTY,0)) end  as SCAN_QTY  from [dbo].[HR_Scan_Record] where BARCODE like 'PL%' and CONVERT(nvarchar(10),SCAN_TIME,120)=CONVERT(nvarchar(10),GETDATE(),120) and LOCATION_CODE='WS_P05_COM5' and STATION_NAME='" + UserName + @"'
            //group by LOCATION_CODE ,STATION_NAME) b on a.LOCATION_CODE=b.LOCATION_CODE and b.STATION_NAME=a.STATION_NAME
            //where a.DEVEICE_COM='WS_P05_COM6'  and a.STATION_NAME='" + UserName + @"'

            //                                    ");
            //CNC_A0.Text = ds.Tables[0].Rows[0]["SCAN_QTY"].ToString();
            //CNC_B0.Text = ds.Tables[1].Rows[0]["SCAN_QTY"].ToString();
            //CNC_C0.Text = ds.Tables[2].Rows[0]["SCAN_QTY"].ToString();
        }
        #region 正则表达式检测是否为数字
        public static bool IsInt(string value)
        {
            return Regex.IsMatch(value, @"^[0-9]*$");
        }
        #endregion

        #region 转换获取工位【LOCATION_CODE】和扫描人【SCANNER_NO】
        public void GetHRInfo(string Location_Code, string BarCode, out string Location_Name, out string Scanner)
        {
            Location_Name = "";
            Scanner = "";
            //工位【LOCATION_CODE】
            DataRow[] dr = dtHR_Station_Info.Select("DEVEICE_COM='" + Location_Code + "'", "LOCATION_CODE ASC");
            if (dr.Length > 0)
            {
                DataTable dtTemp1 = dr.CopyToDataTable();
                Location_Name = dtTemp1.Rows[0]["LOCATION_NAME"].ToString();
            }

            //扫描人【SCANNER_NO】
            if (BarCode.Contains("LMX_TX"))
            {
                DataTable dtWorks = Common.GetDataTable.GetWorksInfo(BarCode);
                if (dtWorks.Rows.Count > 0)
                    Scanner = dtWorks.Rows[0]["WORKER_NAME"].ToString();
            }
            else
            {
                DataTable dtWorkName = Common.GetDataTable.GetWorkName(Location_Name, UserName);
                if (dtWorkName.Rows.Count > 0)
                    Scanner = dtWorkName.Rows[0]["WORKER_NAME"].ToString();
            }

        }
        #endregion
        /// <summary>
        /// 即时发送
        /// </summary>
        /// <param name="StationName"></param>
        /// <param name="BarcodeName"></param>
        private bool SendExpMail(string StationName, string BarcodeName)
        {
            try
            {
                bool result = false;
                DataTable dt = BaseBuildSql.GetDataTableBySql(@" select * from HR_Line_Notice m 
 join (
 select  b.STATION_NAME,a.LOCATION_CODE,b.LOCATION_NAME,a.DUTY_OPERATOR,c.TEL_NO
  from dbo.HR_Location_Record a
 LEFT JOIN HR_Station_Info b ON a.LOCATION_CODE=b.LOCATION_CODE
 LEFT JOIN HR_Workers_Info c ON a.DUTY_OPERATOR=c.WORKER_NO
 where 1=1 and (LOCATION_NAME='科文' or LOCATION_NAME='组长') and ISNULL(a.DUTY_OPERATOR,'')!='') n on m.STATION_NAME=n.STATION_NAME
 join[dbo].[HR_Work_Barcode] k on m.ISSUE_TYPE = k.BARCODE_SN 
 where m.STATION_NAME='" + UserName + "' and m.ISSUE_TYPE='" + BarcodeName + "' ");
                List<string> lst = new List<string>();
                if (dt.Rows.Count != 0)
                {
                    string strMailName = dt.Rows[0]["NOTICE_PERSON_1ST"].ToString();
                    string strMsg = dt.Rows[0]["BARCODE_DESC"].ToString();
                    string strTel = dt.Rows[0]["TEL_NO"].ToString();
                    if (!string.IsNullOrEmpty(strMailName))
                    {

                        string[] Mailers = strMailName.Split(',');
                        string subject = UserName + strMsg;
                        string mailBody = "HELLO:" + strMailName + "\r\n";
                        mailBody += "   您收到一份待处理事项；\r\n";
                        mailBody += "  " + StationName + "&" + strMsg + "&中，请协调处理，谢谢！\r\n";
                        mailBody += "\r\n";
                        mailBody += "\r\n";
                        mailBody += "MES数据采集反馈系统\r\n";
                        mailBody += "Tel:" + strTel + "\r\n";
                        if (EmailHelper.SendLineBarCodeMail(Mailers, mailBody, subject, false))
                            result = true;
                        else
                            result = false;
                    }
                }
                return result;

            }
            catch (Exception ex)
            {

                XtraMessageBox.Show(ex.Message);
                return false;
            }

        }

        /// <summary>
        /// 30分钟后没无处理即时发送
        /// </summary>
        /// <param name="StationName"></param>
        /// <param name="BarcodeName"></param>
        private void AferSendExpMail(string StationName)
        {
            try
            {
                DataTable dtMinute = BaseBuildSql.GetDataTableBySql(@" select DATEDIFF(mi,SCAN_TIME,GETDATE()) as minutes,BARCODE,SCAN_TIME from [dbo].[HR_Scan_Record] where SCAN_TIME in (
                                                                 select  max(SCAN_TIME) as SCAN_TIME from [dbo].[HR_Scan_Record] where BARCODE like '%MES%' ) and STATION_NAME='" + UserName + "' and BARCODE like '%MES%'");
                if (int.Parse(dtMinute.Rows[0]["minutes"].ToString()) >= 3)
                {
                    string workNo = "暂无人";
                    string startDate = dtMinute.Rows[0]["SCAN_TIME"].ToString();
                    DataTable dt = BaseBuildSql.GetDataTableBySql(@" select * from HR_Line_Notice m 
 join (
 select  b.STATION_NAME,a.LOCATION_CODE,b.LOCATION_NAME,a.DUTY_OPERATOR,c.TEL_NO
  from dbo.HR_Location_Record a
 LEFT JOIN HR_Station_Info b ON a.LOCATION_CODE=b.LOCATION_CODE
 LEFT JOIN HR_Workers_Info c ON a.DUTY_OPERATOR=c.WORKER_NO
 where 1=1 and (LOCATION_NAME='科文' or LOCATION_NAME='组长') and ISNULL(a.DUTY_OPERATOR,'')!='') n on m.STATION_NAME=n.STATION_NAME
 join[dbo].[HR_Work_Barcode] k on m.ISSUE_TYPE = k.BARCODE_SN 
 where m.STATION_NAME='" + UserName + "' and m.ISSUE_TYPE='" + dtMinute.Rows[0]["BARCODE"].ToString() + "' ");
                    DataTable dtWorkNo = BaseBuildSql.GetDataTableBySql(@"select top 1* from HR_Scan_Record a
                                                                            left join HR_Workers_Info b on a.BARCODE=b.WORKER_NO
                                                                             where BARCODE like '%LMX%' and SCAN_TIME>'" + startDate + "' order by  SCAN_TIME desc");
                    if (dtWorkNo.Rows.Count > 0)
                        workNo = dtWorkNo.Rows[0]["LOCATION_CODE"].ToString();

                    List<string> lst = new List<string>();
                    if (dt.Rows.Count != 0)
                    {
                        string strMailName = dt.Rows[0]["NOTICE_PERSON_2ND"].ToString();
                        string strMsg = dt.Rows[0]["BARCODE_DESC"].ToString();
                        string strTel = dt.Rows[0]["TEL_NO"].ToString();
                        if (!string.IsNullOrEmpty(strMailName))
                        {
                            string[] Mailers = strMailName.Split(',');
                            string subject = UserName + strMsg;
                            string mailBody = "DEAR," + strMailName + "\r\n";

                            mailBody += "   您收到一份待处理事项；\r\n";
                            mailBody += "  " + UserName + "" + strMsg + "&中，停机/停线时长超过30分钟，" + workNo + "处理中，请协调处理，谢谢！\r\n";
                            mailBody += "\r\n";
                            mailBody += "\r\n";
                            mailBody += "MES数据采集反馈系统\r\n";
                            mailBody += "Tel:" + strTel + "\r\n";

                            EmailHelper.SendLineBarCodeMail(Mailers, mailBody, subject, false);

                            t3.Stop();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }

        }

        /// <summary>
        /// 30
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Timer_TimesUp3(object sender, System.Timers.ElapsedEventArgs e)
        {
            AferSendExpMail(UserName);

        }
        private void SendMailerCheck(string Barcode)
        {
            if (SendExpMail(UserName, Barcode))
            {
                t3 = new System.Timers.Timer(5000 * 12 * 30);
                t3.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp3);
                t3.AutoReset = true;
                t3.Enabled = true;
                t3.Start();
            }
            else
            {
                if (Barcode.Substring(0, 3) == "MES")
                {
                    if (t3 != null)
                    {

                        t3.Stop();
                    }

                }
            }
        }

        private void InitProduct()
        {
            try
            {
                InitLoad();
                string path = @"\\Tx-fs10\tx-fs1\LAMEX\MES\SysSource\Image\Product\" + txtPartBarCode.Text.Trim().Replace("\r", "") + ".jpg";
                if (File.Exists(path))
                {

                    DataTable dtDuty = Lamex.Base.BaseBuildSql.GetDataTableBySql(@"
                                                                               select a.*,c.* from [dbo].[HR_Station_Info] a 
                                                                                left join  HR_Location_Record b on b.LOCATION_CODE=a.LOCATION_CODE
                                                                                left join HR_Workers_Info c on c.WORKER_NO=b.DUTY_OPERATOR
                                                                                 where STATION_NAME = '" + UserName + "'");
                    if (dtDuty.Rows.Count != 0)
                    {
                        string strName = "";
                        int maxLength = dtDuty.AsEnumerable().SelectMany(row => row.ItemArray.OfType<string>()).Max(o => o.Length);

                        foreach (DataRow dr in dtDuty.Rows)
                        {
                            int colLength = dr["LOCATION_NAME"].ToString().Length;
                            int blankLength = maxLength - colLength;
                            string strBlank = "";
                            for (int i = 0; i < blankLength; i++)
                            {
                                strBlank += " ";
                            }
                            strName += strBlank + dr["LOCATION_NAME"].ToString() + "： " + dr["WORKER_NAME"].ToString() + "\r\n";
                        }
                        labelControl1.Text = strName;
                    }

                    string seatPath = @"\\tx-fs10\tx-fs1\LAMEX\MES\SysSource\Image\Product\"+txtPartBarCode.Text.Trim().Replace("\r", "") + ".PNG"; ;
                    if (File.Exists(seatPath))
                    {
                        picTop3.Visible = true;
                        labelControl1.Visible = false;
                        picTop3.Load(seatPath);
                        //picProcess1.Load(QualityPath1);
                    }
                }
                else
                {
                    DataTable dtDuty = Lamex.Base.BaseBuildSql.GetDataTableBySql(@"
                                                                               select a.*,c.* from [dbo].[HR_Station_Info] a 
                                                                                left join  HR_Location_Record b on b.LOCATION_CODE=a.LOCATION_CODE
                                                                                left join HR_Workers_Info c on c.WORKER_NO=b.DUTY_OPERATOR
                                                                                 where STATION_NAME = '" + UserName + "'");
                    if (dtDuty.Rows.Count != 0)
                    {
                        string strName = "";
                        int maxLength = dtDuty.AsEnumerable().SelectMany(row => row.ItemArray.OfType<string>()).Max(o => o.Length);

                        foreach (DataRow dr in dtDuty.Rows)
                        {
                            int colLength = dr["LOCATION_NAME"].ToString().Length;
                            int blankLength = maxLength - colLength;
                            string strBlank = "";
                            for (int i = 0; i < blankLength; i++)
                            {
                                strBlank += " ";
                            }
                            strName += strBlank + dr["LOCATION_NAME"].ToString() + "： " + dr["WORKER_NAME"].ToString() + "\r\n";
                        }
                        labelControl1.Text = strName;
                    }

                    string seatPath = @"\\tx-fs10\tx-fs1\LAMEX\MES\SysSource\Image\Product\"+txtPartBarCode.Text.Trim().Replace("\r", "") + ".PNG"; ;
                    if (File.Exists(seatPath))
                    {
                        picTop3.Visible = true;
                        labelControl1.Visible = false;
                        picTop3.Load(seatPath);
                        //picProcess1.Load(QualityPath1);
                    }

                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }
        
        private void LoadGroupList()
        {
             dtShowHeader = BaseBuildSql.GetDataTableBySql(@"select * from HR_Station_Info where STATION_NAME='" + UserName + "' and LOCATION_NAME not in (select LOCATION_NAME from HR_Station_Info where   STATION_NAME='WS_P05'  and  (LOCATION_NAME='科文' or LOCATION_NAME='组长')) order by LOCATION_CODE desc ");

            //groupControl1.Text = dtShowHeader.Rows[0]["LOCATION_NAME"].ToString() + "实时产量";
            //groupControl3.Text = dtShowHeader.Rows[1]["LOCATION_NAME"].ToString() + "实时产量";;
            //groupControl5.Text = dtShowHeader.Rows[2]["LOCATION_NAME"].ToString() + "实时产量";
            pcBottom.Controls.Clear();
            #region"生成显示控件"
            int i = 0;
            foreach (DataRow dr in dtShowHeader.Rows)
            {
                GroupControl g = new GroupControl();
                g.Name = "gc" + 1;
                g.Text = dr["LOCATION_NAME"].ToString()+ "实时产量";
                g.Dock = DockStyle.Left;
                g.RightToLeft = RightToLeft.No;
                g.ShowCaption = true;
                g.AutoSize = false;
                g.AppearanceCaption.Options.UseTextOptions = true;
                g.AppearanceCaption.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                g.LookAndFeel.UseDefaultLookAndFeel = false;
                LabelControl lb = new LabelControl();
                lb.Appearance.Font = new System.Drawing.Font("Tahoma", 50F, System.Drawing.FontStyle.Bold);
                lb.Appearance.ForeColor = System.Drawing.Color.Blue;
                lb.Appearance.Options.UseFont = true;
                lb.Appearance.Options.UseForeColor = true;
                lb.Appearance.Options.UseTextOptions = true;
                lb.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                lb.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
                lb.Dock = System.Windows.Forms.DockStyle.Fill;
                lb.LineLocation = DevExpress.XtraEditors.LineLocation.Center;
                lb.LineStyle = System.Drawing.Drawing2D.DashStyle.DashDot;
                lb.Text = "0";
                lb.Name= dr["LOCATION_NAME"].ToString();
                //p.Controls.Add(lb);
                g.Controls.Add(lb);
                pcBottom.Controls.Add(g);
                i++;
            }


            #endregion
        }
    }
}